//
//  YijingMainViewController.m
//  TianTianKankan
//
//  Created by sunmingming on 14-8-22.
//  Copyright (c) 2014年 Ebola. All rights reserved.
//

#import "YijingMainViewController.h"
#import "YijingDetailViewController.h"
#import "AFSoundManager.h"
#import "tooles.h"
#import "AppDelegate.h"
#import <LKDBHelper.h>

@interface YijingMainViewController ()<UITableViewDataSource,UITableViewDelegate,AFSoundManagerDelegate>
@property(nonatomic,strong) UIImageView *bgView;
@property(nonatomic,strong) UITableView *mainTableView;

@property(nonatomic,strong) UILabel *songBgLabel;
@property(nonatomic,strong) UILabel *songLogoLabel;
@property(nonatomic,strong) UILabel *songTitleLabel;
@property(nonatomic,strong) UIButton *songPlayButton;
@property(nonatomic,strong) UILabel *musicTimeLabel;
@property(nonatomic,strong) UISlider *musicSlider;

@property(nonatomic,assign) BOOL firstPlay;

-(void)playPressed:(id)sender;

@end

@implementation YijingMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.bgView = [UIImageView new];
        self.bgView.image = [UIImage imageNamed:@"cover.jpg"];
        [self.view addSubview:self.bgView];
        
        self.mainTableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        [self.mainTableView setDelegate:self];
        [self.mainTableView setDataSource:self];
        self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        self.mainTableView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        self.mainTableView.backgroundView = nil;
        [self.view addSubview:self.mainTableView];
        
        self.songBgLabel = [UILabel new];
        self.songBgLabel.text = @"";
        self.songBgLabel.backgroundColor = TitleColor;
        [self.view addSubview:self.songBgLabel];
        
        self.songLogoLabel = [UILabel new];
        self.songLogoLabel.text = @"1";
        self.songLogoLabel.numberOfLines = 1;
        self.songLogoLabel.backgroundColor = [UIColor clearColor];
        self.songLogoLabel.textColor = [UIColor blackColor];
        self.songLogoLabel.font = [UIFont fontWithName:@"Arial" size:17.0f];
        self.songLogoLabel.textAlignment = NSTextAlignmentCenter;
        self.songLogoLabel.hidden = NO;
        [self.view addSubview:self.songLogoLabel];
        
        self.songTitleLabel = [UILabel new];
        self.songTitleLabel.text = @"title";
        self.songTitleLabel.numberOfLines = 1;
        self.songTitleLabel.backgroundColor = [UIColor clearColor];
        self.songTitleLabel.textColor = [UIColor whiteColor];
        self.songTitleLabel.font = [UIFont fontWithName:@"Arial" size:17.0f];
        self.songTitleLabel.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:self.songTitleLabel];
        
        self.musicTimeLabel = [UILabel new];
        self.musicTimeLabel.text = @"--:--";
        self.musicTimeLabel.numberOfLines = 1;
        self.musicTimeLabel.backgroundColor = [UIColor clearColor];
        self.musicTimeLabel.textColor = [UIColor whiteColor];
        self.musicTimeLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        self.musicTimeLabel.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:self.musicTimeLabel];
        
        self.songPlayButton = [[UIButton alloc] init];
        self.songPlayButton.tag = 1;
        [self.songPlayButton setImage:[UIImage imageNamed:@"catalog_group_play_normal.png"] forState:UIControlStateNormal];
        [self.songPlayButton setImage:[UIImage imageNamed:@"catalog_group_pause_normal.png"] forState:UIControlStateSelected];
        [self.songPlayButton addTarget:self action:@selector(playPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.songPlayButton];
        
        self.musicSlider = [UISlider new];
        self.musicSlider.enabled = NO;
        self.musicSlider.tintColor = TitleColor;
        self.musicSlider.minimumTrackTintColor = [UIColor blackColor];
        self.musicSlider.maximumTrackTintColor = [UIColor blackColor];
        self.musicSlider.thumbTintColor = [UIColor whiteColor];
        self.musicSlider.value = 0;
        self.musicSlider.minimumValue = 0;
        self.musicSlider.maximumValue = 1;
        [self.view addSubview:self.musicSlider];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.mainTableView reloadData];
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.firstPlay = YES;
    self.musicSlider.value = 0;
    self.musicTimeLabel.text = @"--:--/--:--";
    self.songPlayButton.selected = NO;
    self.songLogoLabel.text = [NSString stringWithFormat:@"%d",APPALL.globalItem.Page];
    self.songTitleLabel.text = APPALL.globalItem.Title;
    APPALL.globalSoundManager.delegate = self;
    
    WS(ws);
    //TODO use masonry to re-frame all the subviews.
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    
    [self.songBgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ws.view);
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view);
        make.height.mas_equalTo(60);
    }];
    
    [self.mainTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ws.view);
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(self.songBgLabel.mas_top);
        make.top.mas_equalTo(ws.view);
    }];
    
    [self.songLogoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(48, 48));
        make.left.mas_equalTo(ws.view).with.offset(5);
        make.centerY.mas_equalTo(self.songBgLabel);
    }];
    
    [self.songPlayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.songPlayButton.intrinsicContentSize);
        make.right.mas_equalTo(ws.view).with.offset(-5);
        make.centerY.mas_equalTo(self.songBgLabel);
    }];
    
    [self.songTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.songLogoLabel.mas_right).with.offset(5);
        make.right.mas_equalTo(self.songPlayButton.mas_left).with.offset(-5);
        make.bottom.mas_equalTo(self.songBgLabel.mas_centerY);
        make.height.mas_equalTo(20);
    }];
    
    [self.musicTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(80);
        make.right.mas_equalTo(self.songPlayButton.mas_left);
        make.top.mas_equalTo(self.songBgLabel.mas_centerY).with.offset(5);
        make.height.mas_equalTo(20);
    }];
    
    [self.musicSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.songTitleLabel);
        make.right.mas_equalTo(self.musicTimeLabel.mas_left).with.offset(-5);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.musicTimeLabel);
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [APPALL.globalSoundManager stop];
//    APPALL.globalSoundManager.delegate = nil;
    self.songPlayButton.selected = NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)playPressed:(id)sender
{
    UIButton *senderButton = (UIButton*)sender;
    NSLog(@"playPressed :%d",senderButton.tag);
    senderButton.selected = !senderButton.selected;
    if(senderButton.selected)//play
    {
        if(self.firstPlay)
        {
            self.firstPlay = NO;
            [APPALL.globalSoundManager startPlayingLocalFileWithName:[tooles YJMusicNameByIndex:APPALL.globalItem.AudioFilename] withCompletionBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
                if (!error) {
                    NSLog(@"yes! %d,%f,%f,%d",percentage,elapsedTime,timeRemaining,finished);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    [formatter setDateFormat:@"mm:ss"];
                    
                    NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSinceReferenceDate:elapsedTime];
                    
                    NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeRemaining];
                    self.musicTimeLabel.text = [NSString stringWithFormat:@"%@/%@",[formatter stringFromDate:elapsedTimeDate],[formatter stringFromDate:timeRemainingDate]];
                    
                    self.musicSlider.value = percentage * 0.01;
                } else {
                }
            }];
        }
        else
        {
            [APPALL.globalSoundManager resume];
        }
    }
    else
    {
        [APPALL.globalSoundManager pause];
    }
}

-(void)currentPlayingStatusChanged:(AFSoundManagerStatus)status
{
    [self.mainTableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return APPALL.mainBookArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    static NSString *inde = @"editEditableIDCredit2";
    cell = [tableView dequeueReusableCellWithIdentifier:inde];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"EditCellCredit2" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    YJBookItem *cacheItem = [APPALL.mainBookArray objectAtIndex:indexPath.row];
    UIImageView *lab1 = (UIImageView*)[cell viewWithTag:1];
    lab1.hidden = YES;
    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
    lab2.text = cacheItem.Title;
    UIButton *but = (UIButton*)[cell viewWithTag:3];
    [but setTitle:[NSString stringWithFormat:@"%d",indexPath.row + 1] forState:UIControlStateDisabled];
    [but addTarget:self action:@selector(cellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
    lab4.text = [NSString stringWithFormat:@"%d",cacheItem.Page];
    if(self.firstPlay)
    {
        but.selected = NO;
    }
    else if(indexPath.row == APPALL.globalItem.Page - 1)
    {
        but.selected = (APPALL.globalSoundManager.status == AFSoundManagerStatusPlaying);
    }
    else
    {
        but.selected = NO;
    }
    return cell;
}

-(void)cellButtonPressed:(id)sender
{
    UIButton *cacheButton = (UIButton*)sender;
    if(cacheButton.selected)
    {
        //do nothing
    }
    else
    {
        APPALL.nowLevel = [[cacheButton titleForState:UIControlStateDisabled] intValue];
        [tooles setPlistValue:APPALL.nowLevel ForKey:@"level"];
        APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
        NSLog(@"%i,%i",APPALL.nowLevel,APPALL.globalItem.Page);
        self.firstPlay = NO;
        self.songPlayButton.selected = YES;
        self.songLogoLabel.text = [NSString stringWithFormat:@"%d",APPALL.globalItem.Page];
        self.songTitleLabel.text = APPALL.globalItem.Title;
        [APPALL.globalSoundManager startPlayingLocalFileWithName:[tooles YJMusicNameByIndex:APPALL.globalItem.AudioFilename] withCompletionBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
            if (!error) {
                NSLog(@"yes! %d,%f,%f,%d",percentage,elapsedTime,timeRemaining,finished);
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"mm:ss"];
                
                NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSinceReferenceDate:elapsedTime];
                
                NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeRemaining];
                self.musicTimeLabel.text = [NSString stringWithFormat:@"%@/%@",[formatter stringFromDate:elapsedTimeDate],[formatter stringFromDate:timeRemainingDate]];
                
                self.musicSlider.value = percentage * 0.01;
            } else {
                NSLog(@"%@",error);
            }
        }];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //    [self drawChanged:indexPath.row + 1];
    APPALL.nowLevel = indexPath.row + 1;
    APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
    YijingDetailViewController *vc = [[YijingDetailViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

@end
